//
//  XSNewFeatureView.swift
//  XS微博
//
//  Created by 王小帅 on 2016/11/27.
//  Copyright © 2016年 王小帅. All rights reserved.
//

import UIKit

class XSNewFeatureView: UIView {

    @IBOutlet weak var pageCont: UIPageControl!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterBtn: UIButton!
    
    @IBAction func enterStatus(_ sender: Any) {
        IsHidedStatusBar = false
        closeSelf()
        
    }
    
    // 类方法供外界调用
    class func newFeatureView()-> XSNewFeatureView{
    
        // 从xib加载
        let nib = UINib(nibName: "XSNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! XSNewFeatureView
        v.frame = UIScreen.main.bounds
        return v
        
    }
    
    // 设置行特性界面
    override func awakeFromNib() {
        
        // 图片数
        let count = 4
        // 屏幕宽度
        let rect = UIScreen.main.bounds
        
        // 循环想scrollview中加入图片
        for i in 0..<count {
            
            let img = UIImage(named: "new_feature_\(i + 1)")
            let imgView = UIImageView(image: img)
            imgView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(imgView)
            
        }
        // 设置scrollview的属性
        scrollView.frame = rect
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        // 设置代理
        scrollView.delegate = self

        // 隐藏进入按钮
        enterBtn.isHidden = true
        
    }
}



// MARK: - 实现scrollview的代理方法
extension XSNewFeatureView: UIScrollViewDelegate {

    // 当用户开始滑动屏幕
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 设置页码控制器
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageCont.currentPage = page
        // 设置进入按钮显示
        enterBtn.isHidden = (page != scrollView.subviews.count - 1)
        // 当进入最后一页的时候 因此page
        if page == scrollView.subviews.count {
            pageCont.isHidden = true
        }
    }
    
    // 滑动即将结束
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 设置页码控制器
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        pageCont.currentPage = page
        
        // 当进入最后一页的时候 因此page
        if page == scrollView.subviews.count {

            // 设置状态栏
            IsHidedStatusBar = false
            self.closeSelf()
        }
    }
    
    /// 关闭当前视图
    fileprivate func closeSelf(){
        self.removeFromSuperview()
        // 发送关闭通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: NewFeatureAndWeclcomRemoveFromSuperView), object: nil)
        
    }

}
